<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::uses('Sanitize', 'Utility');
/**
 * Newsletters Controller
 *
 * @property Newsletter $Newsletter
 */
class NewslettersController extends AppController {

	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('add','end');
	}
	
	public function beforeRender(){
		parent::beforeRender();
		switch($this->action){
			case 'add':
				$this->layout = 'default';
				break;
			case 'end':
				$this->layout = 'default';
				break;
			case 'check':
				$this->layout = 'ajax';
				break;
			default:
				$this->layout = 'panel';
		}
	
	}
	
/**
 * index method
 *
 * @return void
 */
	public function admin() {
		$this->Newsletter->recursive = 0;
		$options['conditions'] = array('Newsletter.domain_id'=> $this->Session->read('Config.Domain.Domain.id'));
		$this->paginate = $options;
		$this->set('newsletters', $this->paginate());
		
		$this->loadModel('NewsletterMessage');
		$options['conditions'] = array('NewsletterMessage.domain_id'=> $this->Session->read('Config.Domain.Domain.id'));
		$newsletterMessages = $this->NewsletterMessage->find('all',$options);
		$this->set('newsletterMessages',$newsletterMessages);
		
		if(isset($this->passedArgs['szablon']) && !empty($this->passedArgs['szablon'])){
			$newsletterMessage = $this->NewsletterMessage->read(null,$this->passedArgs['szablon']);
			$this->request->data['NewsletterMessage']['subject'] = $newsletterMessage['NewsletterMessage']['subject'];
			$this->request->data['NewsletterMessage']['content'] = $newsletterMessage['NewsletterMessage']['content'];
		}
	}
	
	public function end(){
		$id = $this->Session->read('Newsletter.id');
		if (!$this->Newsletter->exists($id)) {
			throw new NotFoundException(__('Invalid newsletter'));
		}
		$options = array('conditions' => array('Newsletter.' . $this->Newsletter->primaryKey => $id),'Newsletter.domain_id'=> $this->Session->read('Config.Domain.Domain.id'));
		$newsletter = $this->Newsletter->find('first', $options);
		$this->set('newsletter', $newsletter);
		
		$this->podziekowanie($newsletter);
	}
	
	private function podziekowanie($newsletter){
		$email = new CakeEmail();
		try {
			$email->config('smtp');
		} catch(Exception $e) {
			echo 'Config in email.php not found';
			echo $e->getMessage();
			exit;
		}	
	
		$conditions['conditions']['Template.slug'] = 'dziekujemy_za_zgloszenie_na_newsletter';
		$username = $newsletter['Newsletter']['name'];
		$content_ = $this->Templates->parse($conditions, array(
				'imie_nazwisko'=>$username));


		if(is_array($content_)){
			try {
				$content = $content_['Template']['content'];
				$subject = $content_['Template']['subject'];
			
				
				$email->to(Sanitize::clean($newsletter['Newsletter']['email']))
				->subject($subject)
				->send($content);
				
			} catch(Exception $e) {
				echo $e->getMessage();
				exit;
			}
		}
	}
	
	public function check(){
		$this->autoRender = false;
		if ($this->request->is('post')) {
			$id = array_shift(array_keys($this->request->data['Newsltter']));
			$status = $this->request->data['Newsltter'][$id];
			if($id != 'all'){
				$this->Newsletter->id = $id;
				$this->Newsletter->saveField('status', $status);
				$this->Session->write('Newsltter.all',0);
				echo ($status) ? 'On' : 'Off';
			}else if($id == 'all'){
				
				$options = array('Newsletter.domain_id'=> $this->Session->read('Config.Domain.Domain.id'));
				$this->Newsletter->updateAll( array('Newsletter.status' => $status),$options);
				$this->Session->write('Newsltter.all',$status);
				
				echo ($status) ? 'On' : 'Off';
			}
 			
 	
		}
	}
	
	public function send(){
		if($this->request->is('post')) {
			$email = new CakeEmail();
			try {
				$email->config('smtp');
			} catch(Exception $e) {
				echo 'Config in email.php not found';
				exit;
			}
		
			$data = $this->request->data['NewsletterMessage'];
	
			if(isset($this->request->data['NewsletterMessage']['szablon']) && $this->request->data['NewsletterMessage']['szablon'] == 1){
				$this->save_szablon();
			}
			
			$options['conditions'] = array('Newsletter.domain_id'=> $this->Session->read('Config.Domain.Domain.id'),'Newsletter.status'=>1);
			$options['fields'] = array('Newsletter.email','Newsletter.name');
			$users = $this->Newsletter->find('list',$options);
			
			if(is_array($users)){
				foreach ($users as $email_ => $name) {
					$email->to(Sanitize::clean($email_))
					->subject($data['subject'])
					->send(	"Drogi {$name}\n {$data['content']}");									
			}}
			$this->Session->setFlash(__d('contactform', '<script>alert("Wiadomość wysłana pomyślnie")</script>'), '', array('status' => 'success'));
			
		
		}
		
		$this->redirect($this->referer());
	}
	
	
	public function save_szablon(){
		$this->autoRender = false;
		if ($this->request->is('post')) {
			$this->request->data['NewsletterMessage']['domain_id'] = $this->Session->read('Config.Domain.Domain.id');
			$this->loadModel('NewsletterMessage');
			$this->NewsletterMessage->create();
			if ($this->NewsletterMessage->save($this->request->data)) {
				echo __d('newsletter','The newsletter has been saved');				
			} else {
				echo __d('newsletter','The newsletter could not be saved. Please, try again.');
			}
		}
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Newsletter->exists($id)) {
			throw new NotFoundException(__('Invalid newsletter'));
		}
		$options = array('conditions' => array('Newsletter.' . $this->Newsletter->primaryKey => $id),'Newsletter.domain_id'=> $this->Session->read('Config.Domain.Domain.id'));
		$this->set('newsletter', $this->Newsletter->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->request->data['Newsletter']['domain_id'] = $this->Session->read('Config.Domain.Domain.id');
			$this->Newsletter->set( $this->request->data );
			if($this->Newsletter->validates()){				
			
				$this->Newsletter->create();
				if ($this->Newsletter->save($this->request->data)) {
					$this->Session->setFlash(__('The newsletter has been saved'));
					$this->Session->write('Newsletter.id',$this->Newsletter->id);
					$this->redirect(array('action' => 'end'));
				} else {
					$this->Session->setFlash(__('The newsletter could not be saved. Please, try again.'));
					$this->redirect($this->referer());
				}
			}else{
				$this->Session->setFlash(__d('contactform', '<script>alert("E-mail już istnieje")</script>'), '', array('status' => 'success'));
				$this->redirect($this->referer());
			}
		}
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Newsletter->exists($id)) {
			throw new NotFoundException(__('Invalid newsletter'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data['Newsletter']['domain_id'] = $this->Session->read('Config.Domain.Domain.id');
			if ($this->Newsletter->save($this->request->data)) {
				$this->Session->setFlash(__('The newsletter has been saved'));
				$this->redirect(array('action' => 'admin'));
			} else {
				$this->Session->setFlash(__('The newsletter could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Newsletter.' . $this->Newsletter->primaryKey => $id));
			$this->request->data = $this->Newsletter->find('first', $options);
		}
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Newsletter->id = $id;
		if (!$this->Newsletter->exists()) {
			throw new NotFoundException(__('Invalid newsletter'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Newsletter->delete()) {
			$this->Session->setFlash(__('Newsletter deleted'));
			$this->redirect($this->referer());
		}
		$this->Session->setFlash(__('Newsletter was not deleted'));
		$this->redirect($this->referer());
	}
}
